<template>
  <div class="enrollmentall">
    <div class="form">
      <!--      &lt;!&ndash; 筛选条件表单 &ndash;&gt;-->
      <el-form :inline="true" class="filter-form">


        <!--      添加问题-->
        <el-form-item style="">
          <el-button type="success" @click="showUploadDialog">添加用户</el-button>
        </el-form-item>


      </el-form>


      <!-- 招生计划 -->
      <el-table :data="userList" max-height="620"
                @selection-change="handleSelectionChange">

        <!-- 序号列 -->

        <!--        <el-table-column-->
        <!--            type="selection"-->
        <!--        >-->
        <!--        </el-table-column>-->

        <el-table-column type="index" label="序号"></el-table-column>

        <el-table-column label="姓名">
          <template slot-scope="scope">
            <el-input v-model="scope.row.userName"></el-input>
            <!--            <span>{{ // scope.row.name }}</span>-->
          </template>
        </el-table-column>

        <el-table-column label="账号">
          <template slot-scope="scope">
            <!--                        <el-input v-model="scope.row.username"></el-input>-->
            <span>{{ scope.row.userAccount }}</span>
          </template>
        </el-table-column>


        <!--        &lt;!&ndash; 问题答案 &ndash;&gt;:disabled="scope.row.abled"-->
        <el-table-column label="角色">
          <template slot-scope="scope">
            <!--            <el-input v-model="scope.row.province"></el-input>-->
            <span>{{ scope.row.userRole === "user" ? "普通用户" : "管理员" }}</span>
          </template>
        </el-table-column>


        <!-- 操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>

          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="danger" @click="confirmPassword(scope.row.id)">重置密码</el-button>

          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="success" @click="updateUsermessage(scope.row)">修改</el-button>

          </template>
        </el-table-column>

      </el-table>


    </div>
    <!--    <el-button type="text" @click="dialogFormVisible = true">打开嵌套表单的 Dialog</el-button>-->


    <el-dialog title="添加用户" :visible.sync="uploadDialogVisible">
      <el-form>
        <el-form-item label="姓名">
          <el-input v-model="userform.userName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="账号">
          <el-input v-model="userform.userAccount" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="初始密码">
          <el-input v-model="userform.userPassword" autocomplete="off"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetUploadDialog">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="重置密码" :visible.sync="uploadshowDialog">
      <el-form>
        <el-form-item label="密码">
          <el-input v-model="userPassword" autocomplete="off"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetshowDialog">取 消</el-button>
        <el-button type="primary" @click="resetPassword">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import myaxios from "@/config/myaxios";

export default {
  name: "AddUserPage",
  data() {
    return {
      roleList: [],
      userList: [],
      updateUserPermissionshow: false,
      permission: null, //变更权限
      currentUserId: 0,
      userPassword: "", // 用户
      uploadshowDialog:false,
      // priviceList: [], // 常见问题类别
      //
      //
      // carouselFilter: "", // 问题类被筛选条件


      uploadDialogVisible: false, // 上传对话框的显示状态

      userform: {
        userName: null,
        userPassword: null,
        userAccount: null,
        // role: null
      },


    };
  },

  mounted() {
    this.getUserByAll();


  },


  methods: {

    // 变更权限
    updatUserPermission(user) {
      console.log(user)
      this.updateUserPermissionshow = true;
      this.getRoleList()
      this.currentUserId = user.id
      // this.RealupdateUserPermission(user.id)
    },
    // 变更权限
    RealupdateUserPermission() {
      let urlSearchParams = new URLSearchParams;
      urlSearchParams.append("roleid", this.permission)
      urlSearchParams.append("userid", this.currentUserId)
      myaxios.post("roleandPermission/user", urlSearchParams).then(res => {
        if (res.data.code === 0) {
          this.getUserByAll()
          this.permission = null
          this.updateUserPermissionshow = false
          this.$message.success("权限变更成功")
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        // console.log(1)
        this.$message.error("系统繁忙，请稍后重试")
      })

    },
    // 保存用户信息
    saveUser() {
      console.log(this.userform)
      myaxios.post("user/register", this.userform).then(res => {
        if (res.data.code === 0) {
          this.getUserByAll()

        } else {
          this.$message.error(res.data.message)
        }
        this.resetUploadDialog()
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
        this.resetUploadDialog()
      })
    },

    // 多条件获取数据
    getdataByPrivice(plan) {
      myaxios.post("enrollmentplan/classify", plan).then(res => {
        if (res.data.code === 0) {

          this.enrollplan = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
      })
    },

    // 获取用户
    getUserByAll() {
      myaxios.get("user/list").then(res => {
        console.log(res)
        if (res.data.code === 0) {


          this.userList = res.data.data


        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        // console.log(1)
        this.$message.error("系统繁忙，请稍后重试")
      })
    },


    // 删除招生计划
    confirmDelete(user) {
      console.log(user)
      this.$confirm(`确定删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在这里执行删除校园风景的逻辑
        // 可以调用后端接口进行删除操作，或者直接在前端进行删除
        myaxios.post("user/delete", {
          id: user
        }).then(res => {
          if (res.data.code === 0) {
            this.$message.success("删除成功")
            this.getUserByAll() //
          } else {
            this.$message.error(res.data.message)
          }

        }).catch(err => {
          this.$message.error("系统繁忙，请重试")
        })
      }).catch(() => {
        // 用户取消删除
      });
    },


    // 修改表格中每一项的内容
    updateUser(obj) {
      // let urlSearchParams = new URLSearchParams;
      // urlSearchParams.append('id', obj.id)
      // urlSearchParams.append('name', obj.name)
      myaxios.post("user/update", obj).then(res => {
        if (res.data.code === 0) {
          this.$message.success("修改成功")
          this.getUserByAll()
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
      })
    },

    //  修改用户姓名
    updateUsermessage(scope) {
      console.log(scope)
      this.updateUser(scope);
      // var obj = {
      //   "answer": scope.answer,
      //   "content": scope.content,
      //   "id": scope.id
      // }
      // this.updateQuestion(obj)
      // scope.abled = true
    },
    getRoleList: function () {
      myaxios.get("roleandPermission/role").then(res => {
        if (res.data.code === 0) {
          this.roleList = res.data.data
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
      })
    },


    // 显示弹窗
    showUploadDialog() {
      this.uploadDialogVisible = true;
      //  获取角色列表
      // this.getRoleList();
    },

    // 重置弹窗内容
    resetUploadDialog() {
      this.userform.userPassword = null;
      this.userform.userAccount = null;
      this.userform.userName = null;
    },


    cancelUpload() {
      this.resetUploadDialog();
    },


    // 根据问题类别id请求问题
    getquestionByTypeId() {
      myaxios.get("question?typeid=" + this.carouselFilter).then(res => {
        if (res.data.code === 0) {
          let currentPageData = res.data.data;
          // for (var i = 0; i < currentPageData.length; i++) {
          //   currentPageData[i].abled = true
          // }
          this.currentPageData = currentPageData
        } else {
          this.$message.error(res.data.message)
        }
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
      })
    },
    // 当选中列时
    handleSelectionChange(val) {
      console.log(val)
      this.questionDeleteList = val
    },

    //  批量删除函数
    DeleteEnrollplanByIds() {
      //   判断待删除id是否为空
      if (this.questionDeleteList.length === 0) {
        this.$message.error("请选择删除的表单项")
        return
      }
      // console.log( this.questionDeleteList)
      // 提取id

      this.$confirm(`确定批量删除`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {


        var idList = []
        for (var i = 0; i < this.questionDeleteList.length; i++) {
          idList.push(this.questionDeleteList[i].id)
        }

        //  进行删除
        // console.log(idList  )
        let urlSearchParams = new URLSearchParams;
        urlSearchParams.append("longList", idList)
        myaxios.delete("enrollmentplan/batch", {
          params: urlSearchParams
        })
          .then(res => {
            if (res.data.code === 0) {
              this.selectlunbo()
              this.$message.success("删除成功")


            } else {
              this.$message.error(res.data.message)
            }
          }).catch(err => {
          this.$message.error("系统繁忙，请重试")
        })

      }).catch(err => [])


    },


    //  获取excle表格模板
    getExcleTemplete() {
      myaxios.get("question/templete", {
        responseType: "arraybuffer", // 设置响应类型为arraybuffer
      }).then(response => {

        // let blob = new Blob([response.data]); // { type: "application/vnd.ms-excel" }
        // // let filename = response.headers['content-disposition'];
        // let url = window.URL.createObjectURL(blob); // 创建一个临时的url指向blob对象
        // // 创建url之后可以模拟对此文件对象的一系列操作，例如：预览、下载
        // let a = document.createElement("a");
        // a.href = url;
        // a.download = filename;
        // a.click();
        // // 释放这个临时的对象url
        // window.URL.revokeObjectURL(url);


        const fileData = response.data; // 获取文件数据
        const filename = response.headers['content-disposition'].match(/filename="(.*)"/)[1]; // 获取文件名
        console.log(response)
        // 创建一个Blob对象并下载
        let blob = new Blob([fileData], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
        let link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = filename;
        link.click();
      }).catch(error => {
        console.error(error); // 处理文件下载失败
      })
    },

    //  上传表格模板
    showexcleUploadDialog() {
      this.uploadexcleVisible = true;
    },

    //进行表格文件的上传
    addExcle() {

    },
    // 重置表单
    resetexcleUploadDialog() {
      this.$refs.uploadexcle.clearFiles();
      this.uploadexcleVisible = false
    },
    handleexcleUpload(response, file, fileList) {
      // 处理上传的 Excel 文件
      console.log(response, file, fileList)

      if (response.code === 0) {
        this.$message.success("上传成功")
        this.$refs.uploadexcle.clearFiles();
        this.resetexcleUploadDialog()
      } else {
        this.uploadexcleVisible = false
        this.$message.error(response.message)

      }
    },

    beforeexcleUpload(file) {
      const isExcel = file.type === 'application/vnd.ms-excel' || file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      if (!isExcel) {
        this.$message.error('上传文件只能是 Excel 格式!')
      }
      return isExcel
    },

    uploadexcleError(err, file, fileList) {
      // 处理上传错误
      // console.error(err, file, fileList)
      this.$message.error(err)
    },

    // 重置密码
    confirmPassword(id) {
      this.userid = id;
      this.uploadshowDialog = true
    },
    resetshowDialog(){
      this.uploadshowDialog=false
      this.userid=0
    },
    resetPassword(){

      myaxios.post("user/update", {
        id:this.userid,
        userPassword:this.userPassword
      } ).then(res => {
        if (res.data.code === 0) {
          this.$message.success("重置成功")
          this.getUserByAll()
        } else {
          this.$message.error(res.data.message)
        }
        this.resetshowDialog()
      }).catch(err => {
        this.$message.error("系统繁忙，请重试")
        this.resetshowDialog()
      })
    }


    // // 处理每页显示数量的变化
    // handleSizeChange(newSize) {
    //   this.pageSize = newSize;
    //   this.currentPage = 1;
    //   this.updateCurrentPageData();
    // },
    //
    // // 处理当前页码的变化
    // handleCurrentPageChange(newPage) {
    //   this.currentPage = newPage;
    //   console.log("页数改变")
    //   this.getCampausImage()
    //
    //   // this.updateCurrentPageData();
    // },
  },

}
</script>

<style scoped>
.enrollmentall {
  /*padding: 10px;*/
  width: 100%;
}

.form {
  background-color: white;
  padding: 15px;
  margin: 8px;
  border-radius: 10px;
}
</style>
